package com.nbsaas.boot;

import org.codehaus.commons.compiler.CompileException;
import org.codehaus.janino.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DynamicCodeExecutor {
    public static void main(String[] args) {
        // 要执行的动态代码
        String code = "public class DynamicCode { " +
                "public static void execute() { " +
                "System.out.println(\"Dynamic code executed\"); " +
                "} " +
                "}";
        
        try {
            // 创建 ClassBodyEvaluator 对象
            ClassBodyEvaluator evaluator = new ClassBodyEvaluator();
            evaluator.setClassName("DynamicCode");
            evaluator.setDefaultImports(new String[]{"java.lang.*"});
            
            // 编译代码
            evaluator.cook(code);
            
            // 加载并实例化类
            Class<?> clazz = evaluator.getClazz();
            Object obj = clazz.getDeclaredConstructor().newInstance();
            
            // 调用 execute 方法
            Method method = clazz.getMethod("execute");
            method.invoke(obj);
        } catch (CompileException | InstantiationException | IllegalAccessException
                 | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
